package blockchain

import (
	"aqchain/pkg/model"
	"context"
	"gitee.com/aqchain/go-ethereum/core/types"
)

// SubscribeNewHead 订阅新区块事件
func (c *Client) SubscribeNewHead(ctx context.Context) error {
	headerChan := make(chan *types.Header)
	headerSub, err := c.client.SubscribeNewHead(ctx, headerChan)
	if err != nil {
		return err
	}

	for {
		select {
		case <-ctx.Done():
			return ctx.Err()
		case err = <-headerSub.Err():
			return err
		case header := <-headerChan:
			err = c.handleNewHeader(ctx, header)
			if err != nil {
				return err
			}
		}
	}
}

func (c *Client) handleNewHeader(ctx context.Context, header *types.Header) error {

	block, err := c.client.BlockByHash(ctx, header.Hash())
	if err != nil {
		return err
	}
	// 保存区块信息
	blockStorage := model.Block{Number: block.NumberU64()}
	if c.db.First(&blockStorage).RowsAffected > 0 {
		return nil
	}
	blockStorage = model.Block{
		Number:   block.NumberU64(),
		Time:     block.Time().Uint64(),
		Hash:     block.Hash().Hex(),
		TxHash:   block.TxHash().Hex(),
		Coinbase: block.Coinbase().Hex(),
		Size:     float64(block.Size()),
	}
	err = c.db.Create(&blockStorage).Error
	if err != nil {
		return err
	}
	return nil
}
